/**
 * JS File for history.php 
 */


//Load the Visualization API
google.load("visualization", "1", {'packages':['corechart']});

function fetch_data_and_show_chart(days) {
	dojo.byId("messageArea").style.display    = "none";
	dojo.byId("days").value = days;
	
	var type = dijit.byId("history_type").get("value");
	var data = new Array();
	
	for (var i=1;i<5;i++) {
		dojo.byId("HistoryResultsHideMe"+(i)).style.display = "none";
		dojo.byId("HistoryResults"+(i)).innerHTML = "";
	}
		
	var type_text = Array();
	var type_fetch = Array();
	switch (type) {
		case "points": type_text.push( TEXT_ALLYHISTORY_SCORE ); type_fetch.push("points"); break;
		case "epoints": type_text.push( TEXT_ALLYHISTORY_ESCORE ); type_fetch.push("epoints"); break;
		case "fpoints": type_text.push( TEXT_ALLYHISTORY_MSCORE ); type_fetch.push("fpoints"); break;
		case "rpoints": type_text.push( TEXT_ALLYHISTORY_RSCORE ); type_fetch.push("rpoints"); break;
		case "all": 
				type_text.push( TEXT_ALLYHISTORY_SCORE ); type_fetch.push("points");
				type_text.push( TEXT_ALLYHISTORY_ESCORE ); type_fetch.push("epoints");
				type_text.push( TEXT_ALLYHISTORY_MSCORE ); type_fetch.push("fpoints");
				type_text.push( TEXT_ALLYHISTORY_RSCORE ); type_fetch.push("rpoints");
				break;
	}
		
	// check for selections
	var players = new Array();
	var alliances = new Array();
	for (i=1;i<6;i++) {
		var ally_name = dijit.byId("alliance_"+i).get("value");
		if (ally_name != "") {
			try {
				alliances.push(allyStore.query({ allyname: ally_name }).results[0][0].id);
			} catch(ignore) { console.log(ignore); }
		}
		
		var playername = dijit.byId("player_"+i).get("value");
		if (playername != "") {
			try {
				players.push(playerStore.query({ player: playername }).results[0][0].id);
			} catch(ignore) { console.log(ignore); }
		}
	}
	if (players.length + alliances.length < 1) return; // nothing to do
	
	for (i=0;i<type_text.length;i++) {
		dojo.byId("HistoryResults"+(i+1)).innerHTML = TEXT_ALLYHISTORY_TBLHEAD + ": " + type_text[i];
		dojo.byId("HistoryResultsHideMe"+(i+1)).style.display = "block";
		dojo.byId("chart_div"+(i+1)).innerHTML = '<div id="loadingAreaContent"  style="width: 100%; height: 100px;"><img src="../images/loader_big_ogame_bg.gif" style="display:block; margin: 30px auto;" /></div>';

		// fetch all - aggregated by month
		var xhrArgs = {
		        url: "ajax/ajax_history.php?type="+type_fetch[i]+"&chart=chart_div"+(i+1),
		        handleAs: "json",
		        content: { player_data: players.join("|"), ally_data: alliances.join("|"), timespan: days },
		        load: function(jsonData) {
		        	if (jsonData.messages != null) {
		            	showMessages(jsonData.messages);
		        	}
		        	
	        		if (jsonData.data.length > 0) {
	        			galaxytool_drawHistoryChart(jsonData.data, players, alliances, jsonData.chart);
	        		}
		        	
		        },
		        error: function(error) {
					console.log("Error:");
					console.log(error);
		        }
		}	
		dojo.xhrPost(xhrArgs);		
	}
	
	return false; // to avoid form submit
}

function galaxytool_drawHistoryChart(dataSource, players, alliances, chartdiv) {
	
	var data = new google.visualization.DataTable();
	data.addColumn('date', TEXT_REPORTS_DATE);
	var columns = 0; // next one will be column 1 and we need to start counting at 0
	// player columns
	var playerID_2_columnIndex = new Array();
	for (var i=0; i<players.length; i++) {
		columns++;
		data.addColumn('number', playerStore.query({ id: players[i].toString() }).results[0][0].player);
		playerID_2_columnIndex[players[i]] = columns;
	}
	// ally columns
	var allyID_2_columnIndex = new Array();
	for (var i=0; i<alliances.length; i++) {
		columns++;
		data.addColumn('number', allyStore.query({ id: alliances[i].toString() }).results[0][0].allyname);
		allyID_2_columnIndex[alliances[i]] = columns;
	}
	
	/* returning data is formatted like this:
	* [ date as "Y-m-d" or "Y-m",
	*   [ [ playerid , scores ] , [ second_playerid , scores ] ... ],
	*   [ [ allyid, scores ], [second_allyid , scores ] ... ]
	* ] 
	*/
	
	var api_data = new Array();
	for (var i=0; i<dataSource.length; i++) {
		var api_row = new Array(columns+1);
		var date = dataSource[i][0].split("-");
		if (date.length == 3) {
			api_row[0] = new Date(date[0], date[1]-1, date[2]);	
		} else {
			api_row[0] = new Date(date[0], date[1]-1);
		}
		
		for (var p=0; p<dataSource[i][1].length; p++) {
			// player data
			api_row[ playerID_2_columnIndex[dataSource[i][1][p][0]] ] = dataSource[i][1][p][1];
		}
		
		for (var a=0; a<dataSource[i][2].length; a++) {
			// ally data
			api_row[ allyID_2_columnIndex[dataSource[i][2][a][0]] ] = dataSource[i][2][a][1];
		}
		
		api_data.push( api_row );
	}
	
	data.addRows( api_data );

	var formatter = new google.visualization.DateFormat({pattern: 'yyyy-MM-dd'});
	formatter.format(data,0);
	var formatter2 = new google.visualization.NumberFormat({decimalSymbol: ',', groupingSymbol: '.', fractionDigits: 0});
	for (var i=1; i<=columns; i++) {
		formatter2.format(data,i);
	}
	
	var chart = new google.visualization.LineChart(document.getElementById(chartdiv));
	var options = {
			backgroundColor: '#13181D',
            vAxis: {textStyle: { color: '#C4C4C4' } },
            hAxis: {textStyle: { color: '#C4C4C4' }, gridlines: { color: '#13181D' } },
            legend: {textStyle: { color: '#C4C4C4'}},
			interpolateNulls: true,
			pointSize: 5
		}
	chart.draw(data, options);
	
}

function galaxytool_history_init() {
	if (window.location.href.indexOf("p1=") > -1) playerStore.fetch();
	if (window.location.href.indexOf("a1=") > -1) allyStore.fetch();
}

dojo.ready(galaxytool_history_init);